'''
Version: 0.0.1
Author: ider
Date: 2021-02-07 01:42:29
LastEditors: ider
LastEditTime: 2021-05-08 13:00:07
Description: 
'''
from pb import wikitext_pb2
from pb import wikitext_pb2_grpc
import grpc
from concurrent import futures
import time
import logging
import os
from wikitextparser import remove_markup
import multiprocessing
import re

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

rep = re.compile(r"\[|\]|\*|\{|\}")
def easyHandle(text):
    if isinstance(text,str):
        rs = rep.sub("", text)
        rs = rs.replace("&ndash","")
        return rs
    else:
        return ""


class WikiTextPlainServiceServicer(wikitext_pb2_grpc.WikiTextPlainServiceServicer):

    # 实现 proto 文件中定义的 rpc 调用
    def GetWikiTextPlain(self, request, context):

        try:
            size = len(remove_markup(text))
        except Exception as e:
            print("解析异常：",e, text)
            size = len(remove_markup(easyHandle(text)))

        return wikitext_pb2.Visual_Count(count=size)

def startGrpcServer():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=5))
    wikitext_pb2_grpc.add_WikiTextPlainServiceServicer_to_server(WikiTextPlainServiceServicer(),server)
    # 定义服务端端口1234
    server.add_insecure_port('0.0.0.0:11122')
    server.start()

if __name__ == "__main__":
    # 定义开启4个线程处理接收到的请求
    for i in range(30):
        p = multiprocessing.Process(target=startGrpcServer)
        p.start()

    try:
        while True:
            time.sleep(5000)
    except KeyboardInterrupt:
        exit(0)
